% The function averages daily data into weekly ones, the first column must
% contain the dates. Frequency=1 transforms into weekly, Frequency=2
% transforms into monthly. Avg=0 gives EOP, Avg=1 computes the average.
% [lowerFrequencyData]=dailyToLowerFrequency(dailyData,frequency,avg)

function [lowerFrequencyData]=dailyToLowerFrequency(dailyData,frequency,avg)

if frequency==1
    dates=dailyData(:,1);
    eop=find(weekday(dates)==6); %friday
    if avg==1
        lowerFrequencyData(1,:)=[dates(eop(1)), nanmean(dailyData(1:eop(1),2:end),1)];
    else
        rows=endOfPeriod(dailyData,1,eop(1));
        index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
        lowerFrequencyData(1,:)=[dates(eop(1)), dailyData(index)];
    end
    
    for i=2:length(eop)
        if avg==1
            lowerFrequencyData(i,:)=[dates(eop(i)), nanmean(dailyData(eop(i-1)+1:eop(i),2:end),1)];
        else
            rows=endOfPeriod(dailyData,eop(i-1),eop(i));
            index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
            lowerFrequencyData(i,:)=[dates(eop(i)), dailyData(index)];
        end
    end
    
    if eop(end)~=size(dailyData,1)
        if avg==1
            lowerFrequencyData=[lowerFrequencyData;dates(end),nanmean(dailyData(eop(end):end,2:end),1)];
        else
            rows=endOfPeriod(dailyData,eop(end),size(dailyData,1));
            index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
            lowerFrequencyData=[lowerFrequencyData;dates(end),dailyData(index)];
        end
    end
end

if frequency==2
    dates=dailyData(:,1);
    eop=find(month(dates(1:end-1))~=month(dates(2:end)));
    if avg==1
        lowerFrequencyData(1,:)=[datenum(year(dates(eop(1))),month(dates(eop(1)))+1,1)-1, nanmean(dailyData(1:eop(1),2:end),1)];
    else
        rows=endOfPeriod(dailyData,1,eop(1));
        index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
        lowerFrequencyData(1,:)=[datenum(year(dates(eop(1))),month(dates(eop(1)))+1,1)-1, dailyData(index)];
    end
    
    for i=2:length(eop)
        if avg==1
            lowerFrequencyData(i,:)=[datenum(year(dates(eop(i))),month(dates(eop(i)))+1,1)-1, nanmean(dailyData(eop(i-1)+1:eop(i),2:end),1)];
        else
            rows=endOfPeriod(dailyData,eop(i-1),eop(i));
            index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
            lowerFrequencyData(i,:)=[datenum(year(dates(eop(i))),month(dates(eop(i)))+1,1)-1, dailyData(index)];
        end
    end
    
    if eop(end)~=size(dailyData,1)
        if avg==1
            lowerFrequencyData=[lowerFrequencyData;dates(end),nanmean(dailyData(eop(end):end,2:end),1)];
        else
            rows=endOfPeriod(dailyData,eop(end),size(dailyData,1));
            index=rows+[1:size(dailyData,2)-1]*size(dailyData,1);
            lowerFrequencyData=[lowerFrequencyData;dates(end),dailyData(index)];
        end
    end
end

end